export default class Drawer {
  constructor(canvas, mapInfo, tileSrcMap) {
    this.currentTileId = 0
    this.canvas = canvas
    this.mapInfo = mapInfo
    this.tileSize = 40
    this.tileSrcMap = tileSrcMap
    this.tiles = this.mapInfo.tiles
    this.context = this.canvas.getContext('2d')
    this.cache = new Image()
    this.setCanvasSize()
    this.canPaint = false
    this.isEditing = false
  }
  setCanvas(canvas) {
    this.canvas = canvas
    this.context = this.canvas.getContext('2d')
    this.setCanvasSize()
  }
  setMapInfo(mapInfo) {
    this.mapInfo = mapInfo
    this.tiles = mapInfo.tiles
  }
  setSrcMap(map) {
    this.tileSrcMap = map
  }
  setData(canvas, mapInfo) {
    this.setCanvas(canvas)
    this.setMapInfo(mapInfo)
  }
  setCanvasSize() {
    if (!this.mapInfo) throw new Error('没有地图数据！')
    const width = this.tileSize * this.mapInfo.width
    const height = this.tileSize * this.mapInfo.height
    this.canvas.width = width
    this.canvas.height = height
  }
  render() {
    this.tiles.forEach((arr, i) => {
      arr.forEach((id, j) => {
        this.cache.src = this.tileSrcMap[id]
        this.context.drawImage(this.cache, this.tileSize * i, this.tileSize * j, this.tileSize, this.tileSize)
      })
    })
  }
  setCurrentTileId(id){
    this.currentTileId = id
  }
  setCanPaint(){
    if(this.canPaint) return
    this.canPaint = true
    this.canvas.addEventListener('mousedown',(e)=>{
      this.isEditing = true
      this.paintMap(e)
    })
    this.canvas.addEventListener('mouseup',()=>{
      this.isEditing = false
    })
    this.canvas.addEventListener('mousemove',(e)=>{
      this.paintMap(e)
    })
  }
  paintMap(e){
    if(!this.isEditing) return
    let x = Math.floor( e.layerX / this.tileSize)
    let y = Math.floor( e.layerY / this.tileSize)
    if(this.mapInfo.tiles[x][y] == this.currentTileId) return
    let src = this.tileSrcMap[this.currentTileId]
    this.mapInfo.tiles[x][y] = this.currentTileId
    this.cache.src = src
    this.context.drawImage(this.cache,x*this.tileSize,y*this.tileSize,this.tileSize,this.tileSize)
  }
}
